package com.ezlcp.gateway.utils;

import com.alibaba.nacos.common.utils.StringUtils;
import java.util.StringJoiner;
import java.util.regex.Pattern;

/**
 * @author Elwin ZHANG
 * @description: 跨域脚本攻击和SQL注入处理工具<br />
 * @date 2023/2/1 13:57
 */
public class XssCleanRuleUtils {
    private static final String[] xssScriptRegArr = {
            "<script>(.*?)</script>",
            "src[\r\n]*=[\r\n]*\\'(.*?)\\'",
            "</script>",
            "<script(.*?)>",
            "eval\\((.*?)\\)",
            "expression\\((.*?)\\)",
            "javascript:",
            "vbscript:",
            "onload(.*?)=",
            "truncate\\s+table\\s+f_",
            "drop\\s+table\\s+f_",
            "drop\\s+database\\s+f_",
            "rename\\s+table\\s+f_",
            "\\/\\*",
            "--\\s+",
            "use\\s+"
    };
    private static StringJoiner joiner = new StringJoiner("|");
    private static Pattern xssPattern = null;

    static {
        for (String reg : xssScriptRegArr) {
            joiner.add(reg);
        }
        xssPattern = Pattern.compile(joiner.toString(), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    }

    private XssCleanRuleUtils() {

    }

    /**
     * xssClean
     * @param value
     * @return
     */
    public static String xssClean(String value) {
        if (StringUtils.isEmpty(value)) {
            return value;
        }

        value = xssPattern.matcher(value).replaceAll("&lt;XssScript&gt;***&lt;/XssScript&gt;");
        value = value.replace("<", "&lt;").replace(">", "&gt;");

        return value;
    }
}